﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using System.Net;
using Newtonsoft.Json;

namespace Elight.WebApi.Filters
{
    /// <summary>
    /// 表示一个特性，该特性用于全局捕获程序运行异常信息。
    /// </summary>
    public class ExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        private readonly ILogger<ExceptionHandlingAttribute> _logger;
        private readonly IHostingEnvironment _env;

        public ExceptionHandlingAttribute(IHostingEnvironment env, ILogger<ExceptionHandlingAttribute> logger)
        {
            _logger = logger;
            _env = env;
        }

        public override void OnException(ExceptionContext context)
        {
            //var code = HttpStatusCode.InternalServerError; // 500 if unexpected

            //if (exception is exc) code = HttpStatusCode.NotFound;
            //else if (exception is UnauthorizedException) code = HttpStatusCode.Unauthorized;
            //else if (exception is Exception) code = HttpStatusCode.BadRequest;

            //var result = JsonConvert.SerializeObject(new { error = exception.Message });
            //context.Response.ContentType = "application/json";
            //context.Response.StatusCode = (int)code;
            //return context.Response.WriteAsync(result);

            var exception = context.Exception;

            string requestHost = context.HttpContext.Request.Host.ToString();
            string requestPath = context.HttpContext.Request.Path.ToString();
            string queryString = context.HttpContext.Request.QueryString.ToString();

            _logger.LogWarning(new EventId(exception.HResult), exception, exception.Message);

            if (!_env.IsDevelopment())
            {
                context.Result = new RedirectResult("https://www.baidu.com/");
            }

            context.ExceptionHandled = true;
        }
    }
}
